class ImageService
  include StatusObject
  include Serviceable

  def initialize(params, object, options ={})
    @params = params
    @object = object
    @options = options
  end

  def call
    if !@options.present? #create
      create_images
    else #update
      update_images
    end
    Status.new(success: true, notice: 'Ok')
  rescue => e
    Rails.logger.error "报错是#{e.message}"
    Status.new(success: false, notice: e.message)
  end

  private
  def create_images
    @params.each_with_index do |item, i|
      image = item[1]["image"]
      status = QiniuService.call(image.path, image.original_filename, @object)
      if status.success?
        Rails.logger.info "当前状态是qiniu回调在success里"
        @object.images.create!(image: status.notice["key"], store_id: @object.store_id)
      end
    end
  end

  def update_images
    image_ids = @object.images.ids.map(&:to_s)
    if @params.present?
      @params.each do |key, value|
        image = value["image"]
        status = QiniuService.call(image.path, image.original_filename, @object)
        if status.success?
          if image_ids.include?(key.to_s) && value["image"].present?
            obj_image = @object.images.find(key)
            obj_image.update!(image: status.notice["key"])
          elsif !image_ids.include?(key.to_s) && value["image"].present?
            @object.images.create!(image: status.notice["key"], store_id: @object.store_id)
          end
        end
      end
    end
  end

end
